WorldSaver = class()
WorldSaver.FileHead = "TinyCraft World Data"
WorldSaver.Version = "0002"

function WorldSaver:init()
    self.chunkSaver = ChunkSaver()
end

function WorldSaver:save() 
    local cs = self.chunkSaver
    local h = "Documents:"..world.name .. "-"
    for i,chunk in pairs(world.chunkManager.chunks) do
        if chunk.changed then
            cs:saveChunk(chunk,h .. i)
        end
    end
    local tdata = json.encode(self:generateWorldDate(world))
    saveText("Documents:".."TCSave",tdata)
end

function WorldSaver:read()
    local tdate = readText("Documents:TCSave")
    if tdate == nil then return false end
    if tdate == "" then return false end
    
    local date = json.decode(tdate)
    
    if date[1] ~= WorldSaver.FileHead then
        return false,"不是TC的存档文件"
    end
    if date[2] ~= WorldSaver.Version then 
        return false,"存档版本不适用"
    end
    
    local worldInfo = WorldInfo()
    worldInfo:readData(date[3])
    
    local world = World(worldInfo)
    world.chunkManager.readMode = true
    
    return world
end

function WorldSaver:readChunk(chunkIndex)
    chunkIndex = "Documents:"..world.name .. "-" .. chunkIndex
    return self.chunkSaver:readChunk(world,chunkIndex)
end

function WorldSaver:saveChunk(chunk,chunkIndex)
    if chunk.changed then
        chunkIndex = "Documents:"..world.name .. "-" .. chunkIndex
        self.chunkSaver:saveChunk(chunk,chunkIndex)
    end
end

function WorldSaver:generateWorldDate(world)
    local date = {}
    date[1] = WorldSaver.FileHead
    date[2] = WorldSaver.Version
    date[3] = world:getWorldInfo():generateData()
    -- date[5] = player:generateData()
    return date
end

function WorldSaver:testFile(worldFile)
    local tdate = readText(worldFile)
    if tdate == nil then return false end
    if tdate == "" then return false end
    
    local date = json.decode(tdate)
    
    if date[1] ~= WorldSaver.FileHead then
        return false
    end
    if date[2] ~= WorldSaver.Version then 
        return false
    end
    
    return true
end

function WorldSaver:getWorldInfo(worldFile)
    if not self:testFile(worldFile) then return end
    local date = json.decode(readText(worldFile))
    local worldInfo = WorldInfo()
    worldInfo:readData(date[3])
    return worldInfo
end
